package com.zy.je.common.core.utils.lang;


import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.text.StrUtil;

/**
 * @author zy
 */
@Slf4j
public class StackUtil {
    private static final StackWalker STACK_WALKER = StackWalker.getInstance();

    public static String getCallerMethodName(int skip) {
        return STACK_WALKER.walk(stackFrames -> stackFrames
                .skip(skip) // 跳过getCurrentMethodName方法本身
                .findFirst()
                .map(StackWalker.StackFrame::getMethodName)
                .orElse(""));
    }

    public static String getCallerNameWithLineNum(int skip) {
        StackWalker.StackFrame caller = getCaller(skip);
        if(null==caller){
            return "";
        }
        return StrUtil.format("{}.{}:{} ", caller.getFileName(), caller.getMethodName(), caller.getLineNumber());
    }

    public static StackWalker.StackFrame getCaller(int skip) {
        return STACK_WALKER.walk(stackFrames -> stackFrames
                .skip(skip)
                .findFirst()
                .orElse(null));
    }

    public static void main(String[] args) {
        testCaller(2);
    }

    private static void testCaller(int skip) {
        log.debug(getCallerNameWithLineNum(skip));
    }
}
